<template>
    <div v-if="!isEdit" flex="cross:center">
        <button size="mini" type="primary" plain style="margin-right: 10rpx;" @click="downloadPdf"> 文档下载</button>
        <button size="mini" type="primary" plain @click="previewPdf">生成文件预览</button>
    </div>
</template>

<script>
// import { downloadPdf } from '@/api/module'
export default {
    data() {
        return {
            isEdit: false
        }
    },
    props: {
        pdfDownload: {
            type: Boolean,
            default: false
        },
        title: {
            type: String,
            default: ''
        },
        keyId: {
            type: [String, Number],
            default: ''
        },
        formData: {
            type: Object,
            default: () => ({})
        },
        moduleName: {
            type: String,
            default: ''
        }
    },
    methods: {
        /*
          默认 pdfDownload = false ，如果是 pad端，就通过 postMessage 调用 uni-app 的方法来打开pad浏览器新页面
          之后，浏览器打开的页面仍然是此页面，此时 pdfDownload = true,再次点击按钮则为下载pdf。之后需要手动打开汉小印app去打印了
        */
        async downloadPdf() {
            console.log(this.moduleName);
            let res = await this.$u.api.record.downloadPdf(this.formData, { moduleName: this.moduleName })
            const URI = res.data.pdfPath

            uni.downloadFile({
                url: URI, //仅为示例，并非真实的资源
                success: (res) => {
                    if (res.statusCode === 200) {
                        console.log('下载成功', res.tempFilePath);
                        uni.saveFile({
                            tempFilePath: res.tempFilePath,
                            success: (res) => {
                                var savedFilePath = res.savedFilePath;
                            }
                        });
                        uni.openDocument({
                            filePath: res.tempFilePath,
                            success: (res) => {
                                console.log(res, '文件打开成功');
                            }
                        })
                    }
                }
            });
        },
        async previewPdf() {
            let res = await this.$u.api.record.downloadPdf(this.formData, { moduleName: this.moduleName })
            const URI = res.data.pdfPath
            uni.navigateTo({
                url: '/pages/common/pdfWebview?fileUrl=' + encodeURIComponent(URI)
            })
        }
    }
}
</script>
<style scoped lang="scss">
.download-btn {
    button {
        background-color: #ecf5ff;
    }
}
</style>